<template>
  <a-modal v-model:open="open" :title="fromModel.id?'编辑':'新增'"
           cancel-text="取消"
           :confirm-loading="confirmLoading" @ok="handleOk"
           @cancel="close"
           @close="close"
           width="100%"
           wrap-class-name="full-modal"
  >
    <div>
      <a-form
          ref="formRef"
          :model="fromModel"
          :rules="rules"

      >
        <a-form-item label="文章标题" name="title">
          <a-input v-model:value="fromModel.title"
                   placeholder="文章标题"
                   allow-clear/>
        </a-form-item>

       <a-form-item label="分类" name="categoryId">
         <a-select v-model:value="fromModel.categoryId"
                   placeholder="请选择分类"
                   allow-clear

         >
           <a-select-option
               v-for="item in categoryList"
               :key="item.id"
               :value="item.id">
             {{item.name}}
           </a-select-option>
         </a-select>
       </a-form-item>
       <a-form-item label="关键词" name="keywords"

       >
         <a-input v-model:value="fromModel.keywords"
                  placeholder="关键词"

                  allow-clear/>
       </a-form-item>

      <a-form-item label="文章封面地址" name="avatar"
      html-for="{null}"
      >
        <image-upload v-model="fromModel.avatar"/>
      </a-form-item>
      <a-form-item label="文章简介" name="summary">
          <a-textarea v-model:value="fromModel.summary"
                   placeholder="文章简介"
                      :auto-size="{ minRows: 2, maxRows: 5 }"
                      show-count :maxlength="200"
                   allow-clear/>
      </a-form-item>
<!--      <a-form-item label="文章内容 （最多两百字）" name="content">
          <a-input v-model:value="fromModel.content"
                   placeholder="文章内容 （最多两百字）"
                   allow-clear/>
      </a-form-item>
      <a-form-item label="文章内容md版" name="contentMd">
          <a-input v-model:value="fromModel.contentMd"
                   placeholder="文章内容md版"
                   allow-clear/>
      </a-form-item>-->
        <a-space>
          <a-form-item label="是否置顶" name="isStick">
            <a-switch v-model:checked="fromModel.isStick"
                      :un-checked-value="0"
                      :checked-value="1"
                      allow-clear/>
          </a-form-item>
          <a-form-item label="是否发布" name="publishStatus">
            <a-switch v-model:checked="fromModel.publishStatus"
                      :un-checked-value="0"
                      :checked-value="1"
                      allow-clear/>
          </a-form-item>
          <a-form-item label="是否原创" name="isOriginal">
            <a-switch v-model:checked="fromModel.isOriginal"
                      :un-checked-value="0"
                      :checked-value="1"
                      allow-clear/>
          </a-form-item>
          <a-form-item label="是否首页轮播" name="isCarousel">
            <a-switch v-model:checked="fromModel.isCarousel"
                      :un-checked-value="0"
                      :checked-value="1"
                      allow-clear/>
          </a-form-item>
          <a-form-item label="是否推荐" name="isRecommend">
            <a-switch v-model:checked="fromModel.isRecommend"
                      :un-checked-value="0"
                      :checked-value="1"
                      allow-clear/>
          </a-form-item>
        </a-space>
<!--        <div style="border: 1px solid #ccc">
          <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
          />
          <Editor
              style="height: 500px; overflow-y: hidden;"
              v-model="fromModel.contentMd"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleCreated"
          />
        </div>-->
        <MdEditor v-model="fromModel.contentMd" @onUploadImg="onUploadImg"/>
      </a-form>
    </div>
  </a-modal>
</template>
<script setup lang="ts">
import {
  ref, defineProps, defineEmits,
  watch, onMounted, defineComponent
} from 'vue'
  import {add,edit} from '@/api/article/index.ts'
  import {querySelectList} from '@/api/article/category.ts'
  import {uploadFile} from '@/api'

  import imageUpload from '@/components/image-upload/index.vue'
/*  import '@wangeditor/editor/dist/css/style.css' // 引入 css
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'*/

import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
  defineComponent({
    /*Editor,
    Toolbar*/
    imageUpload
  })
  const props = defineProps(['row','modelValue']);
  const emits = defineEmits(['update:modelValue','success']);
  const generateFromModel = ()=>{
    return{
        id: 0,
        categoryId: null,
        title: '',
        avatar: '',
        summary: '',
        content: '',
        contentMd: '',
        isStick: 0,
        publishStatus: 1,
        isOriginal: 1,
        originalUrl: '',
        address: '',
        isCarousel: 0,
        isRecommend: 0,
        keywords: '',
    }
  }
  const fromModel = ref(generateFromModel());
  const open = ref(false)
  const confirmLoading = ref(false);
  const formRef = ref();
  const categoryList = ref<any[]>([])
  const baseImgUrl = import.meta.env.VITE_BASE_IMG_URL;


  const rules = {
     categoryId: [
       { required: true, message: '分类不能为空', trigger: 'blur' }
     ],
     title: [
       { required: true, message: '文章标题不能为空', trigger: 'blur' }
     ],
     avatar: [
       { required: true, message: '文章封面地址不能为空', trigger: 'blur' }
     ],
     summary: [
       { required: true, message: '文章简介不能为空', trigger: 'blur' }
     ],
     /*content: [
       { required: true, message: '文章内容 （最多两百字）不能为空', trigger: 'blur' }
     ],*/
     contentMd: [
       { required: true, message: '文章内容md版不能为空', trigger: 'blur' }
     ],

     isStick: [
       { required: true, message: '是否置顶 0否 1是不能为空', trigger: 'blur' }
     ],
     isPublish: [
       { required: true, message: '是否发布 0：下架 1：发布不能为空', trigger: 'blur' }
     ],
     isOriginal: [
       { required: true, message: '是否原创  0：转载 1:原创不能为空', trigger: 'blur' }
     ],
     originalUrl: [
       { required: true, message: '转载地址不能为空', trigger: 'blur' }
     ],
     address: [
       { required: true, message: '发布地址不能为空', trigger: 'blur' }
     ],
     quantity: [
       { required: true, message: '文章阅读量不能为空', trigger: 'blur' }
     ],
     isCarousel: [
       { required: true, message: '是否首页轮播不能为空', trigger: 'blur' }
     ],
     isRecommend: [
       { required: true, message: '是否推荐不能为空', trigger: 'blur' }
     ],
     keywords: [
       { required: true, message: '关键词不能为空', trigger: 'blur' }
     ]
      }
  const close = ()=>{
    fromModel.value = generateFromModel();
    confirmLoading.value = false;
    emits('update:modelValue',false)
  }
  const handleOk = ()=>{
    formRef.value
        .validate()
        .then(async () => {
          confirmLoading.value = true;
          if (fromModel.value.id){
            await edit(fromModel.value);
          }else {
            await add(fromModel.value)
          }
          confirmLoading.value = false;
          emits('success')
        })
        .catch(error => {
          confirmLoading.value = false;
          console.log('error', error);
        })
  }
  const getCategoryList = ()=>{
    querySelectList().then((res:any)=>{
      categoryList.value = res.result;
    })
  }


  watch(()=>props.row,(value)=>{
    if(value){
      fromModel.value = {...value}
    }
  }, {
    immediate:true,
    deep:true
  })
  watch(()=>props.modelValue,(value)=>{
    open.value = value;
    if(value){
      getCategoryList();
    }
  },{
      immediate:true
  })
watch(()=>fromModel.value.avatar,(value)=>{
  console.log('avatar',value)
},{
  immediate:true
})
const onUploadImg = async (files, callback) => {
  const res = await Promise.all(
      files.map((file) => {
        return new Promise((rev, rej) => {
          uploadFile(file).then((respon:any)=>{
            rev(respon.result)
          })
        });
      })
  );
  console.log(res)

  // 方式二
  callback(
    res.map((item:string)=>{
      const fileName = item.slice(item.lastIndexOf("/")+1,item.length)
      return{
        url:baseImgUrl+'/'+ item,
        alt: fileName,
        title: fileName
      }
    })
  );
};

  onMounted(()=>{

  })
</script>
<style lang="scss">
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: auto;
  }
  .ant-modal-body {
    flex: 1;
  }
}
</style>
